/*
 * Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.cloudapp.ui.activity;

import static com.huawei.cloudapp.utils.CasConstantsUtil.COMMON;
import static com.huawei.cloudapp.utils.CasConstantsUtil.IAM_USERNAME;
import static com.huawei.cloudapp.utils.CasConstantsUtil.MANAGEMENT;
import static com.huawei.cloudapp.utils.CasConstantsUtil.PHONE_ID;
import static com.huawei.cloudapp.utils.CasConstantsUtil.PROJECT_ID;
import static com.huawei.cloudapp.utils.CasConstantsUtil.REGION_ID;
import static com.huawei.cloudapp.utils.CasConstantsUtil.REGION_NAME;
import static com.huawei.cloudapp.utils.CasConstantsUtil.SELECTED_REGION_POSITION;
import static com.huawei.cloudapp.utils.CasConstantsUtil.SESSION_ID;
import static com.huawei.cloudapp.utils.CasConstantsUtil.TOKEN;
import static com.huawei.cloudapp.utils.CasConstantsUtil.TOKEN_EXPIRE_TIME;
import static com.huawei.cloudapp.utils.CasConstantsUtil.USERNAME;
import static com.huawei.cloudapp.utils.CasConstantsUtil.USER_INFO;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.viewpager.widget.ViewPager;

import com.huawei.cloudapp.model.bean.direct.ServerList;
import com.huawei.cloudapp.presenter.PhonePresenter;
import com.huawei.cloudapp.R;
import com.huawei.cloudapp.model.IHandleData;
import com.huawei.cloudapp.model.IPhoneModel;
import com.huawei.cloudapp.common.CasCommonDialog;
import com.huawei.cloudapp.common.CasRecord;
import com.huawei.cloudapp.model.bean.CustomException;
import com.huawei.cloudapp.model.bean.User;
import com.huawei.cloudapp.ui.views.CasArcView;
import com.huawei.cloudapp.model.bean.PhoneInfo;
import com.huawei.cloudapp.ui.adapter.CardPagerAdapter;
import com.huawei.cloudapp.ui.common.ShadowTransformer;
import com.huawei.cloudapp.utils.CasCommonUtils;

import java.util.HashMap;
import java.util.List;


public class CasCloudMainManagementActivity extends Activity implements IHandleData<PhoneInfo> {

    private static final String TAG = "CasCloudMainActivity";
    private static final int MSG_GET_START_PARAM_RESPONSE = 102;
    private static final double PADDING_VIEW_RATIO = 4;
    private static final int LIMIT = 30;
    private ViewPager mViewpager;
    private CardPagerAdapter mCardPagerAdapter;
    private ShadowTransformer mShadowTransformer;
    private CasArcView arcView;
    private CasRecord mCasRecord;
    private User mUserInfo;
    private ServerList.Server mServer = null;
    private String mRegion;
    private boolean isLogin = false;
    private int mOffset = 0;
    private Button appConnect;
    private CasCommonDialog mDialog;
    private int mSelectPhoneIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cas_cloud_main_management);
        appConnect = findViewById(R.id.app_connect);
        appConnect.setVisibility(View.GONE);
    }

    private void initView() {
        mViewpager = findViewById(R.id.viewPager);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        int physicalWidth = metrics.widthPixels;
        int physicalHeight = metrics.heightPixels;
        double paddingLeftAndRight = (physicalWidth - (physicalWidth * PADDING_VIEW_RATIO / (1 + PADDING_VIEW_RATIO))) / 2;
        double paddingTopAndBottom = (physicalHeight - ((physicalWidth - paddingLeftAndRight * 2) * 16 / 9)) / 2;
        mViewpager.setPadding((int) paddingLeftAndRight, (int) paddingTopAndBottom, (int) (paddingLeftAndRight), (int) paddingTopAndBottom);

        arcView = findViewById(R.id.arcView);
        ViewGroup.LayoutParams layoutParams = arcView.getLayoutParams();
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        layoutParams.height = physicalHeight / 4;
        arcView.setLayoutParams(layoutParams);

        FrameLayout.LayoutParams buttonLayoutParams = (FrameLayout.LayoutParams) appConnect.getLayoutParams();
        buttonLayoutParams.setMargins(0, 0, 0, physicalHeight / 10);
        buttonLayoutParams.height = physicalHeight / 16;
        buttonLayoutParams.width = physicalWidth / 3;
        appConnect.setLayoutParams(buttonLayoutParams);

        mViewpager.setAdapter(mCardPagerAdapter);
        mViewpager.setOffscreenPageLimit(3);
        mViewpager.setCurrentItem(mSelectPhoneIndex);
        mShadowTransformer = new ShadowTransformer(mViewpager, mCardPagerAdapter);
        mShadowTransformer.enableScaling(true);
        mViewpager.setPageTransformer(false, mShadowTransformer);
        appConnect.setText(R.string.button_connect_cloud_phone);
        appConnect.setVisibility(View.VISIBLE);
    }

    private void GetUserPhoneList(User userInfo) {
        if (mCardPagerAdapter != null && mCardPagerAdapter.getCount() != 0) {
            return;
        }

        if (!CasCommonUtils.isDirectMode()) {
            mRegion = MANAGEMENT;
        } else {
            CasRecord mCommonRecord = new CasRecord(getSharedPreferences(COMMON, MODE_PRIVATE));
            String selectedRegionPosition = mCommonRecord.getRecord(SELECTED_REGION_POSITION);
            if (selectedRegionPosition == null || selectedRegionPosition.isEmpty()) {
                mRegion = REGION_NAME.get(6);
            } else {
                mRegion = REGION_NAME.get(Integer.parseInt(selectedRegionPosition));
            }
        }

        String projectId = "";
        if (!userInfo.getUserProjectId().isEmpty()) {
            projectId =  userInfo.getUserProjectId().get(mRegion);
        }

        HashMap<String, String> condition = new HashMap<>();
        IPhoneModel phoneModel;
        if (CasCommonUtils.isDirectMode()) {
            Intent intent = getIntent();
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                mServer = intent.getParcelableExtra(ServerList.Server.BUNDLE_KEY);
                condition.put("server_id", mServer.getServerId());
            }
            phoneModel = new com.huawei.cloudapp.model.direct.PhoneModel();
        } else {
            phoneModel = new com.huawei.cloudapp.model.management.PhoneModel();
        }

        PhonePresenter phonePresenter = new PhonePresenter(this, phoneModel);
        phonePresenter.getPhoneList(userInfo, condition, mRegion, projectId, mOffset, LIMIT);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mCasRecord = new CasRecord(getSharedPreferences(USER_INFO, MODE_PRIVATE));
        String username = mCasRecord.getRecord(USERNAME);
        if (username == null || username.isEmpty()) {
            getSharedPreferences(USER_INFO, MODE_PRIVATE).edit().clear().apply();
            Intent intent = new Intent(CasCloudMainManagementActivity.this, CasCloudLoginActivity.class);
            startActivity(intent);
            finish();
        } else {
            mUserInfo = new User(username,
                    mCasRecord.getRecord(IAM_USERNAME),
                    mCasRecord.getHashMapRecord(TOKEN),
                    mCasRecord.getHashMapRecord(TOKEN_EXPIRE_TIME),
                    mCasRecord.getHashMapRecord(PROJECT_ID),
                    mCasRecord.getRecord(SESSION_ID));
            isLogin = true;
            GetUserPhoneList(mUserInfo);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mDialog && mDialog.isShowing()) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    public void onUserViewClick(View view) {
        if (!isLogin) {
            Intent intent = new Intent(CasCloudMainManagementActivity.this, CasCloudLoginActivity.class);
            startActivity(intent);
            finish();
        } else {
            showLogoutUserDialog(mUserInfo.getUsername());
        }
    }

    public void showLogoutUserDialog(String username) {
        if (mDialog == null || !mDialog.isShowing()) {
            final View contentView = View.inflate(this, R.layout.cas_set_ui_level, null);
            final CasCommonDialog.Builder builder = new CasCommonDialog.Builder(this);
            CasCommonDialog.DialogClickListener dialogListener = new CasCommonDialog.DialogClickListener();

            builder.setTitle(username);
            builder.setContentView(contentView);
            builder.setPositiveButton(getResources().getString(R.string.cas_phone_cancel_tip_message), dialogListener);
            builder.setNegativeButton(getResources().getString(R.string.cas_phone_quit_app_tip_message), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    getSharedPreferences(USER_INFO, MODE_PRIVATE).edit().clear().apply();
                    Intent intent = new Intent(CasCloudMainManagementActivity.this, CasCloudLoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            });

            mDialog = builder.create();
            mDialog.setCancelable(true);
            if (!this.isFinishing()) {
                mDialog.show();
            }
        }
    }

    public void cloudPhoneDebug(View view) {
//        if (!CasCommonUtils.onJumpToDebugView()) {
//            return;
//        }
//        Intent intent = new Intent(CasCloudManagementMainActivity.this, CasCloudDebugActivity.class);
//        startActivity(intent);
    }

    public void cloudPhoneConnect(View view) {
        if (CasCommonUtils.isFastClick() || !isLogin) {
            return;
        }
        startCloudPhoneActivity(CasCloudPhoneActivity.class);
    }

    private void startCloudPhoneActivity(Class<?> cls) {
        Intent intent = new Intent(CasCloudMainManagementActivity.this, cls);

        if (mViewpager != null && mCardPagerAdapter != null && mCardPagerAdapter.getCount() == 0) {
            return;
        }
        int index = 0;
        if (mViewpager != null) {
            index = mViewpager.getCurrentItem();
        }
        mSelectPhoneIndex = index;
        String phoneId = mCardPagerAdapter.getCardItem(index).getPhoneId();
        if (phoneId.isEmpty()) {
            return;
        }
        intent.putExtra(PHONE_ID, phoneId);
        intent.putExtra(User.BUNDLE_KEY, mUserInfo);
        intent.putExtra(REGION_ID, mRegion);

        startActivity(intent);
        overridePendingTransition(0, 0);
    }

    @Override
    public void handleData(List<PhoneInfo> list, int count) {

        mCardPagerAdapter = new CardPagerAdapter(this);
        for (PhoneInfo phoneInfo : list) {
            if (phoneInfo.getPhoneId().isEmpty() || phoneInfo.getName().isEmpty()) {
                Log.e(TAG, "handleGetPhoneListResponse: failed to parse response json str ");
                return;
            }
            mCardPagerAdapter.addCardItem(phoneInfo);
        }
        mOffset += LIMIT;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mCardPagerAdapter.getCount() == 1) {
                    startCloudPhoneActivity(CasCloudPhoneActivity.class);
                    finish();
                } else {
                    initView();
                }
            }
        });
    }

    @Override
    public void handleError(Exception e) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (e instanceof CustomException.LogInInfoInvalidException) {
                    Toast.makeText(CasCloudMainManagementActivity.this, getResources().getString(R.string.user_info_invalid_need_login), Toast.LENGTH_SHORT).show();
                    getSharedPreferences(USER_INFO, MODE_PRIVATE).edit().clear().apply();
                    Intent intent = new Intent(CasCloudMainManagementActivity.this, CasCloudLoginActivity.class);
                    startActivity(intent);
                    finish();
                } else if (e instanceof CustomException.EmptyResponseFromServerException ||
                        e instanceof CustomException.FailedToGetPhoneListException) {
                    Toast.makeText(CasCloudMainManagementActivity.this, getResources().getString(R.string.failed_to_get_phone_list), Toast.LENGTH_SHORT).show();
                } else {
                    Log.e(TAG, "handleError: ", e);
                }
            }
        });

    }
}